package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApArticleElasticSearchService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApArticleStaticHtml;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ApArticleServiceImpl implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleStaticHtml apArticleStaticHtml;
    @Autowired
    private ApArticleElasticSearchService apArticleElasticSearchService;

    /**
     * 页面数据展示
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult loadArticleList(ArticleHomeDto dto, short type) {
        //1.校验参数是否存在(查询的数据条数)
        Integer size = dto.getSize();
        if (size == null || size == 0){
            //指定查询条数
            size =10;
        }
        size = Math.min(size, ArticleConstants.MAX_PAGE_SIZE);
        //2.校验参数类型
        //3.校验频道参数是否存在，不存默认查询
        if (StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //4.校验最大时间和最小时间时间是否存在
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        //4.调用数据访问成查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, type);
        //5.封装数据返回
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 自媒体发布文章审核通过就，将文章内容保存到app端对应的文章表中
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        //0.校验参数是否存在
        if (articleDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto,article);
        //2.判断自媒体是新增文章还是修改文章
        if (articleDto.getId() == null){
            //2.1自媒体发布的是新增文章，app端保存内容到表中（有三个表：基础表：ap_article，配置表：ap_article_config，内容表：ap_article_config）
            //2.1.1新增文章基础信息到基础表
            apArticleMapper.insert(article);
            //2.1.2新增文章配置信息到配置表
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(article.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfigMapper.insert(apArticleConfig);
            //2.1.3新增文章内容表到内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(article.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //2.2自媒体发布的是修改文章（配置表信息不用修改）
            //2.2.1修改文章基础信息到基础表
            apArticleMapper.updateById(article);
            //2.2.2修改文章内容表到内容表
            LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleContent::getArticleId,article.getId());
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(queryWrapper);
            apArticleContent.setContent(articleDto.getContent());

            apArticleContentMapper.updateById(apArticleContent);
        }

        //调用文章静态页面的方法生成静态页面
        apArticleStaticHtml.buildApArticleStaticHtml(article,articleDto.getContent());

        //调用服务将文章保存到ES中
        apArticleElasticSearchService.saveArticleToElasticSearch(article,articleDto.getContent());

        //新增或修改完成，返回结果
        return ResponseResult.okResult(article.getId());
    }

    @Override
    public ResponseResult<ApArticle> findById(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getAuthorId,id);
        ApArticle apArticle = apArticleMapper.selectOne(queryWrapper);
        return ResponseResult.okResult(apArticle);
    }

}
